package password

import (
	"context"
	"errors"

	"gitee.com/hexug/devcloud/mcenter/apps"
	"gitee.com/hexug/devcloud/mcenter/apps/token"
	"gitee.com/hexug/devcloud/mcenter/apps/token/provider"
	"gitee.com/hexug/devcloud/mcenter/apps/user"
	"gitee.com/hexug/devcloud/mcenter/common/logger"
	"github.com/google/uuid"
)

var _ provider.Issuer = (*issuer)(nil)

type issuer struct {
	svc user.Server
}

func (i *issuer) Init() error {
	i.svc = apps.GetApp(user.AppName).(user.Server)
	return nil
}
func (i *issuer) IssuerToken(ctx context.Context, in *token.IssueTokenRequest) (*token.Token, error) {
	dr := user.NewDetailUserRequestByUsername(in.Username)
	// fmt.Println(i.svc)
	u, err := i.svc.DetailUser(ctx, dr)
	if err != nil {
		logger.L().Errorw(err.Error())
		return nil, errors.New("用户名或者密码不正确")
	}
	if err = u.CheckPassword(in.Password); err != nil {
		logger.L().Errorw(err.Error())
		return nil, errors.New("用户名或密码不正确")
	}
	t := token.NewToken()
	t.AccessToken = uuid.NewString()
	t.RefreshToken = uuid.NewString()
	t.UserId = u.Meta.Id
	t.Username = u.Spec.Username
	t.Type = token.TOKEN_TYPE_BEARER
	t.GrantType = token.GRANT_TYPE_PASSWORD
	t.Status.IsBlock = false
	return t, nil
}
func init() {
	provider.Registry(token.GRANT_TYPE_PASSWORD, &issuer{})
}
